package com.learning_paicoding.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.learning_paicoding.dto.UserLoginDTO;
import com.learning_paicoding.dto.UserRegisterDTO;
import com.learning_paicoding.entity.User;
import com.learning_paicoding.mapper.UserMapper;
import com.learning_paicoding.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learning_paicoding.utils.JWTUtils;
import com.learning_paicoding.utils.RedisCache;
import com.learning_paicoding.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * <p>
 * 用户登录表 服务实现类
 * </p>
 *
 * @author hph
 * @since 2025-07-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisCache redisCache;


    @Override
    public User getByTelephone(String telephone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("telephone", telephone);
        User userInfo = userMapper.selectOne(queryWrapper);
        return userInfo;
    }

    @Override
    public User checkToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        Map<String, Object> map = JWTUtils.checkToken(token);
        if (map == null) {
            return null;
        }

        String userJson =  redisCache.getCacheObject(token);
        if (StringUtils.isEmpty(userJson)) {
            return null;
        }
        User user = JSON.parseObject(userJson, User.class);
        return user;
    }
}
